package com.buss.FrontController;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.areainfo.entity.AreaInfoEntity;
import com.buss.artcomments.entity.BnsArticleCommentsEntity;
import com.buss.article.entity.BnsArticleEntity;
import com.buss.articlegroup.entity.ArticleGroupInfoEntity;
import com.buss.articlegroup.service.ArticleGroupInfoServiceI;
import com.buss.theme.entity.BnsThemeEntity;
import com.buss.user.entity.BnsUsersInfoEntity;



/**   
 * @Title: Controller
 * @Description: 前台文章控制层
 * @author hlg
 * @date 2016-09-03
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/frontArticleInfoController")
public class FrontArticleInfoController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(FrontArticleInfoController.class);

	@Autowired
	private ArticleGroupInfoServiceI articleGroupInfoService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private CommonService commonService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 文章详情和评论列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "articleInfoList", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView articleInfo(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		BnsUsersInfoEntity userInfo = (BnsUsersInfoEntity) session.getAttribute("LOCAL_FRONT_USER");
		if (!StringUtil.isNotEmpty(userInfo)) {
			return new ModelAndView("front/login");
		}
		
		String id = request.getParameter("Id");
		
		Long dataCount = 0L;
		int pageParam = 0;
		String page = request.getParameter("page");
		if (StringUtil.isEmpty(page)) {
			pageParam = 0;
		} else {
			pageParam = Integer.parseInt(page);
		}
		CriteriaQuery cq = new CriteriaQuery(BnsArticleCommentsEntity.class);

		
		BnsArticleEntity articleInfo = systemService.getEntity(BnsArticleEntity.class, id);
		
		int browseNum = articleInfo.getBrowseNum()+1;
		articleInfo.setBrowseNum(browseNum); 
		systemService.updateEntitie(articleInfo); //更新查看数
		
//		String articleId =  articleInfo.getGroupId();
		AreaInfoEntity areaInfo = systemService.getEntity(AreaInfoEntity.class, articleInfo.getAreaId());
		ArticleGroupInfoEntity articleGroupInfo = systemService.getEntity(ArticleGroupInfoEntity.class, articleInfo.getGroupId());
		
		String articleId = articleInfo.getId().toString();
		//查询出分页评论
		dataCount = systemService.getCountForJdbcParam("select count(1) from bns_article_comments where article_id='" + articleId + "'", null);
		
		cq.eq("articleId", articleId); // 限制条件
		cq.setPageSize(10);
		cq.setCurPage(pageParam);
		cq.add();
		List<BnsArticleCommentsEntity> articleCommentsList = systemService.getListByCriteriaQuery(cq, true);
		
		int pageCount = 0;
		if (dataCount.intValue() > 0 && dataCount.intValue() % 10 == 0) {
			pageCount = dataCount.intValue() / 10;
		} else {
			pageCount = dataCount.intValue() / 10 + 1;
		}
		request.setAttribute("pageCount", pageCount);
		
//		List<BnsArticleCommentsEntity> articleCommentsList = systemService.findByProperty(BnsArticleCommentsEntity.class, "articleId", articleId);
		
		BnsThemeEntity themeInfo = systemService.getEntity(BnsThemeEntity.class, articleInfo.getThemeId());
		request.setAttribute("areaInfo", areaInfo);
		request.setAttribute("articleGroupInfo", articleGroupInfo);
		request.setAttribute("themeInfo", themeInfo);
		request.setAttribute("articleInfo", articleInfo);
		request.setAttribute("articleCommentsList", articleCommentsList);
		
		return new ModelAndView("front/articleInfo");
	}
	

	/**
	 * 发表评论
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "sendComments")
	public ModelAndView sendComments(HttpServletRequest request, HttpServletResponse response) {
		String path = "front/login";
		HttpSession session = request.getSession();
		AjaxJson j = new AjaxJson();
		message = "评论成功";
		String mbId = "";
		Object mbIdV = session.getAttribute("mbId");
		if (!StringUtil.isNotEmpty(mbIdV)) {
			return new ModelAndView("front/login");
		}
		String userName = session.getAttribute("userName").toString();

		// try {
		mbId = mbIdV.toString();
		String content = request.getParameter("content");
		String articleId = request.getParameter("articleId");
		String commentsId = request.getParameter("commentsId");	//引用评论者内容

		BnsArticleCommentsEntity myArticleComments = new BnsArticleCommentsEntity();
		
		myArticleComments.setCommentsType("0"); 
		myArticleComments.setCommentsContent(content);
		myArticleComments.setCreateBy(mbId);
		myArticleComments.setCreateName(userName);
		myArticleComments.setCreateDate(new Date());
		myArticleComments.setArticleId(articleId);
		
		String sql = "select * from bns_article_comments where article_id='"+articleId+"' ORDER BY floor_num DESC LIMIT 1"; 
		List<Map<String, Object>> resultsList =commonService.findForJdbc(sql, null);
		int froor = 2;
		if(resultsList.size()>0){ 
			froor = (Integer)resultsList.get(0).get("floor_num");
			froor +=1;
		}
		myArticleComments.setFloorNum(froor); 
		
		// 保存实体
		commonService.save(myArticleComments);
		
		BnsArticleEntity articleInfo = systemService.getEntity(BnsArticleEntity.class, articleId);
		articleInfo.setCommentsNum(articleInfo.getCommentsNum()+1); 
		articleInfo.setLastreplyId(mbId);
		articleInfo.setLastreplyCtime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		articleInfo.setLastreplyName(userName); 
		commonService.updateEntitie(articleInfo);	//更新评论数、浏览数
		
		path = "redirect:/frontArticleInfoController.do?articleInfoList&Id=" + articleId + "";	//保存帖子 成功重定向到保存的帖子详情
		return new ModelAndView(path);
	}
	
	/**
	 * 回复楼主
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "replyLz")
	@ResponseBody
	public AjaxJson replyLz(HttpServletRequest request, HttpServletResponse response) {
		String path = "front/login";
		HttpSession session = request.getSession();
		AjaxJson j = new AjaxJson();
		message = "回复成功";
		String mbId = "";
		Object mbIdV = session.getAttribute("mbId");
		if (!StringUtil.isNotEmpty(mbIdV)) {
			j.setMsg("请登录");
			return j;
		}
		String userName = session.getAttribute("userName").toString();
		mbId = mbIdV.toString();
		String content = request.getParameter("content");
		String articleId = request.getParameter("articleId");
		BnsArticleEntity articleInfo = systemService.getEntity(BnsArticleEntity.class, articleId);
		
		BnsArticleCommentsEntity myArticleComments = new BnsArticleCommentsEntity();
		myArticleComments.setCommentsType("0"); 
		myArticleComments.setCommentsContent(content);
		myArticleComments.setCreateBy(mbId);
		myArticleComments.setCreateName(userName);
		myArticleComments.setCreateDate(new Date());
		myArticleComments.setArticleId(articleId);
		myArticleComments.setCommentsId(articleInfo.getCreateName());
		
		String sql = "select * from bns_article_comments where article_id='"+articleId+"' ORDER BY floor_num DESC LIMIT 1"; 
		List<Map<String, Object>> resultsList =commonService.findForJdbc(sql, null);
		int froor = 2;
		if(resultsList.size()>0){ 
			froor = (Integer)resultsList.get(0).get("floor_num");
			froor +=1;
		}
		myArticleComments.setFloorNum(froor); 
		
		// 保存实体
		commonService.save(myArticleComments);
		
		
		articleInfo.setCommentsNum(articleInfo.getCommentsNum()+1); 
		articleInfo.setLastreplyId(mbId);
		articleInfo.setLastreplyCtime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		articleInfo.setLastreplyName(userName); 
		commonService.updateEntitie(articleInfo);	//更新评论数、浏览数
		
		j.setMsg("回复成功");
		j.setSuccess(true);
		return j;
	}
	
	/**
	 * 保存回复
	 * 
	 * @param saveReply
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(params = "saveReply")
	@ResponseBody
	public AjaxJson saveReply( HttpServletRequest request) throws Exception{
		String path = "front/login";
		HttpSession session = request.getSession();
		String mbId = "";
		Object mbIdV = session.getAttribute("mbId");
		AjaxJson j = new AjaxJson();
		if (!StringUtil.isNotEmpty(mbIdV)) {
			j.setMsg("请登录");
			return j;
		}else {
			mbId = mbIdV.toString();
			String content = request.getParameter("content");	//回复内容
			String articleId = request.getParameter("articleId");	//当前文章Id
//			String createName = request.getParameter("createName");	//回复评论者
			String quote = request.getParameter("quote");	//引用
			String quoteId = request.getParameter("quoteId");	//引用
			String commentsId = request.getParameter("commentsId");	//引用评论者ID
			String quoteTitle = request.getParameter("quoteTitle");	//引用标题
//			String quoteContent = request.getParameter("quoteContent");	//引用内容
			String userName = session.getAttribute("userName").toString();
			
			BnsArticleCommentsEntity quoteComments = systemService.getEntity(BnsArticleCommentsEntity.class, quoteId);
			
			
			BnsArticleCommentsEntity myArticleComments = new BnsArticleCommentsEntity();
			
			// 用于区分 是评论 还是回复评论
			if(StringUtil.isNotEmpty(quote)){
				myArticleComments.setCommentsType("1");
				myArticleComments.setCommentsId(commentsId); 
				// TODO 需要保存引用标题和引用内容 在评论表里添加 这2个字段 
				
				myArticleComments.setCreateBy(mbId);
				myArticleComments.setCreateName(userName);
				myArticleComments.setCreateDate(new Date());
				myArticleComments.setArticleId(articleId);
				myArticleComments.setCommentsContent(content);
				myArticleComments.setReplyTitle(quoteTitle);
				myArticleComments.setReplyContent(quoteComments.getCommentsContent());	
				String sql = "select * from bns_article_comments where article_id='"+articleId+"' ORDER BY floor_num DESC LIMIT 1"; 
				List<Map<String, Object>> resultsList =commonService.findForJdbc(sql, null);
				int froor = 2;
				if(resultsList.size()>0){ 
					froor = (Integer)resultsList.get(0).get("floor_num");
					froor +=1;
				}
				myArticleComments.setFloorNum(froor); 
				
				// 保存实体
				commonService.save(myArticleComments);
				
				BnsArticleEntity articleInfo = systemService.getEntity(BnsArticleEntity.class, articleId);
				articleInfo.setCommentsNum(articleInfo.getCommentsNum()+1); 
				articleInfo.setLastreplyId(mbId);
				articleInfo.setLastreplyCtime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
				articleInfo.setLastreplyName(userName); 
				commonService.updateEntitie(articleInfo);	//更新评论数、浏览数
				
			}
			j.setMsg("回复成功");
			j.setSuccess(true);
			return j;
			
		}
		
	}
	
	@RequestMapping(params = "goList")
	public ModelAndView goList(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) {
		String articleId = request.getParameter("articleId");
		String path = "redirect:/frontArticleInfoController.do?articleInfoList&Id=" + articleId + "";	//保存帖子 成功重定向到保存的帖子详情
		return new ModelAndView(path);
	}
	
	/**
	 * 添加回复楼主页面跳转
	 */
	@RequestMapping(params = "replyOriginal")
	public ModelAndView replyOriginal(HttpServletRequest request, HttpServletResponse response){
		
		String path = "front/login";
		HttpSession session = request.getSession();
		AjaxJson j = new AjaxJson();
		String mbId = "";
		Object mbIdV = session.getAttribute("mbId");
		if (!StringUtil.isNotEmpty(mbIdV)) {
			return new ModelAndView(path);
		}
		String userName = session.getAttribute("userName").toString();
		
		// try {
		mbId = mbIdV.toString();
		
		String articleId = request.getParameter("articleId");
		
		
		BnsArticleEntity articleInfo = systemService.getEntity(BnsArticleEntity.class, articleId);
		
		request.setAttribute("articleInfo",articleInfo);
		return new ModelAndView("front/replyOriginal");
	}
	
	/**
	 * 添加回复页面跳转
	 */
	@RequestMapping(params = "reply")
	public ModelAndView reply(HttpServletRequest request, HttpServletResponse response){
		
		String path = "front/login";
		HttpSession session = request.getSession();
		AjaxJson j = new AjaxJson();
		String mbId = "";
		Object mbIdV = session.getAttribute("mbId");
		if (!StringUtil.isNotEmpty(mbIdV)) {
			return new ModelAndView(path);
		}
		String userName = session.getAttribute("userName").toString();

		// try {
		mbId = mbIdV.toString();
		
		String plId = request.getParameter("plId");
		
		
		BnsArticleCommentsEntity commentsInfo = systemService.getEntity(BnsArticleCommentsEntity.class,plId);
		
		request.setAttribute("commentsInfo",commentsInfo);
		return new ModelAndView("front/quoteReply");
	}
	
	
}
